# gozerbot/backup.py
#
#

""" backup thread .. only make backup if filesize has grown """

__copyright__ = 'this file is in the public domain'

from gozerbot.config import config
from gozerbot.generic import rlog, handle_exception
from gozerbot.datadir import datadir
import os, shutil, time

backupstop = 0

# backup thread
def backup():
    """ backup thread """
    rlog(0, 'backup', 'starting backup thread')
    # check for config vars
    backupdir = config['backupdir']
    if not backupdir:
        backupdir = 'backup'
    backupsleep = config['backupsleep']
    if not backupsleep:
        backupsleep = 60
    # check if backup dir exists .. if not create it
    if not os.path.isdir(backupdir):
        os.mkdir(backupdir)

    def filesize(src):
        """ function to determine file size """ 
        return os.stat(src)[6]

    # get lists of file in backup dir
    backupfiles = os.listdir(backupdir)

    # dict to hold filesizes
    filesizes = {}
    # determine file sizes
    for i in backupfiles:
        if i.endswith('.tmp'):
            continue
        filesizes[i] = filesize(backupdir + '/' + i)

    while not backupstop:
        try:
            # get list of files in datadir
            datafiles = os.listdir(datadir)
            # for each file check data size and if file has grown copy it
            for datafile in datafiles:
                dfilename = datadir + '/' + datafile
                if dfilename.endswith('.tmp'):
                    continue
                bfilename = backupdir + '/' + datafile
                if os.path.isdir(dfilename):
                    continue
                doit = 0
                dsize = filesize(datadir + '/' + datafile)
                if datafile not in filesizes:
                    doit = 1
                elif dsize > filesizes[datafile]:
                    doit = 1
                if doit:
                    rlog(5, 'backup', 'making backup of %s' % datafile)
                    shutil.copyfile(dfilename, bfilename)
                    filesizes[datafile] = dsize
        except Exception, ex:
            handle_exception()
        time.sleep(backupsleep)
    rlog(5, 'backup', 'stopping backup thread')
